<template>
  <!-- 登录页面 -->
  <view class="page">
    <view class="logo">
      <image src="../../static/logo.png" mode=""></image>
    </view>
    <!-- 填写区 -->
    <view class="input-info">
      <view class="info">
        <input type="tel" maxlength="11" v-model="form.phone" placeholder="手机号">
        <view class="more"></view>
      </view>
      <view class="info" :style="isLoginWay?'':'display: none'">
        <input type="tel" v-model="form.code" maxlength="6" placeholder="请输入验证码">
        <view class="more">
          <text class="mo">获取验证码</text>
          <text class="mo" style="display: none">59秒后重试</text>
        </view>
      </view>
      <view class="info" :style="isLoginWay?'display: none':''">
        <input :password='!isPassword' v-model="form.password" maxlength="26" placeholder="请输入密码">
        <view class="more">
          <text class="iconfont" :class="isPassword?'icon-eye-on':'icon-eye-off'"
            @click="isPassword = !isPassword"></text>
          <text class="mo">忘记密码</text>
        </view>
      </view>
    </view>
    <!-- 按钮 -->
    <view class="btn-info">
      <view class="btn" :style="isLogin?'opacity:1':'opacity:0.4'" @click="isLogin?onLogin():''">
        <text>登录</text>
      </view>
    </view>
    <!-- 操作 -->
    <view class="operation">
      <text @click="onLoginCut">{{isLoginWay?'手机号密码登录':'短信验证码登录'}}</text>
      <text @click="onRegister">新用户注册</text>
    </view>
    <!-- 其他方式登录 -->
    <view class="other-ways">
      <text>其他登录方式</text>
    </view>
    <!-- 登录方式 -->
    <view class="login-way">
      <view class="way" lang="zh_CN" @tap="getUserProfile">
        <!-- <button type="primary" lang="zh_CN" @tap="getUserProfile">新版微信登录</button> -->
        <!-- <button open-type="getUserInfo" @getuserinfo="getUserInfo"> 旧版登录-->
        <image src="/static/wx_ico.png" mode=""></image>
        <!-- </button> -->

        <text>微信登录</text>
      </view>
    </view>
  </view>
</template>

<script>
  // 按需导入mapState, mapMutations, mapGetters 辅助函数
  import {
    mapState,
    mapMutations,
    mapGetters
  } from 'vuex'
  export default {
    data() {
      return {
        isLogin: false,
        isLoginWay: false,
        isPassword: false,
        userInfo:{},
        nickName:'',
        avatarUrl:'',
        // 表单
        form: {
          phone: '',
          code: '',
          password: '',
        },
      };
    },
    computed: {
      // 2. 从 m_user 模块中导入需要的 token 字符串
      ...mapState('m_user', ['token']),
    },
    methods: {
      onRegister() {
        uni.navigateTo({
          url: '/subpkg2/register/register'
        })
      },
      /**
       * 登录切换
       */
      onLoginCut() {
        this.isLoginWay = !this.isLoginWay;
        // 验证码
        if (this.isLoginWay) {
          this.isLogin = this.form.code && this.form.phone ? true : false;
        }
        // 账号密码
        if (!this.isLoginWay) {
          this.isLogin = this.form.password && this.form.phone ? true : false;
        }
      },
      /**
       * 登录点击
       */
      onLogin() {},
      // 2. 调用 mapMutations 辅助方法，把 m_user 模块中的 updateUserInfo 映射到当前组件中使用
      ...mapMutations('m_user', ['updateUserInfo', 'updateToken']),
      // 获取微信用户的基本信息
      // getUserInfo(e) { //旧版
      //   console.log("========================")
      //   console.log(e)
      //   // 判断是否获取用户信息成功
      //   if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')

      //   // 获取用户信息成功， e.detail.userInfo 就是用户的基本信息
      //   console.log(e.detail.userInfo)
      //   this.userInfo=e.detail.userInfo;
      //   // 3. 将用户的基本信息存储到 vuex 中
      //   this.updateUserInfo(e.detail.userInfo)
      //   // 获取登录成功后的 Token 字符串
      //   this.getToken(e.detail)
      // },
      getUserProfile() { //新版登录
        uni.getUserProfile({
          lang: 'zh_CN',
          desc: '用于获取您的个人信息',
          success: res => {
            console.log("hhh====新版====================>>>>>>>>")
            console.log(res)

            // 获取用户信息成功，
            console.log(res.userInfo)
            this.userInfo=res.userInfo;
            this.avatarUrl=res.userInfo.avatarUrl;
            this.nickName=res.userInfo.nickName;
            // // 3. 将用户的基本信息存储到 vuex 中
            // this.updateUserInfo(res.userInfo)
            // 获取登录成功后的 Token 字符串
            this.getToken(res)
          },
          fail: err => { //err
            // 判断是否获取用户信息成功
            if (err.errMsg === 'getUserProfile:fail auth deny') return uni.$showMsg('您取消了登录授权！')
          },
          complete: res => { //final

          }
        })
      },
      // 调用登录接口，换取永久的 token
      async getToken(info) {
        // 调用微信登录接口
        const [err, res] = await uni.login().catch(err => err)
        console.log(res)
        // 判断是否 uni.login() 调用失败
        if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
        // 准备参数对象
        const query = {
          code: res.code,
          encryptedData: info.encryptedData,
          iv: info.iv,
          rawData: info.rawData,
          signature: info.signature
        }
        //预登陆
        console.log("res.code=====================>>>>>>>>>>>>>>>>>>")
        console.log(res.code)

        const {
          data: res2
        } = await uni.$http.post('/login/wxBeforeLogin', res.code)
        console.log("res2=====================>>>>>>>>>>>>>>>>>>")
        console.log(res2)


        // 调用后台api接口  【换取 token】 
        const {
          data: loginResult
        } = await uni.$http.post('/login/wxLogin', query)
        console.log("loginResult=====================>>>>>>>>>>>>>>>>>>")
        console.log(loginResult)
        if (loginResult.status !== 200) return uni.$showMsg('登录失败！')
        uni.$showMsg('登录成功')
        console.log("登录成功")
        console.log(loginResult);
        // this.userInfo.openId=loginResult.data.openId;
        // this.userInfo.userId=loginResult.data.userId;
        this.userInfo=loginResult.data;
        // 3. 将用户的基本信息存储到 vuex 中
        this.updateUserInfo(this.userInfo)
        // 2. 更新 vuex 中的 token
        this.updateToken(loginResult.data.token)
        setTimeout(() => {
          console.log("======================================")
          console.log(this.avatarUrl)
          console.log(this.nickName)
          // uni.reLaunch({
          //   url: '/pages/vipcard/vipcard?nickName=' + this.nickName+'&avatarUrl='+this.avatarUrl
          // })
          uni.navigateBack({
            
          })
          
          // uni.switchTab({
          //   url:'/pages/vipcard/vipcard'
          // })
        }, 1500)

      }
    },
    watch: {
      form: {
        handler(newValue, oldValue) {
          // 验证码
          if (this.isLoginWay) {
            this.isLogin = newValue.code && newValue.phone ? true : false;
          }
          // 账号密码
          if (!this.isLoginWay) {
            this.isLogin = newValue.password && newValue.phone ? true : false;
          }
        },
        deep: true
      }
    }
  }
</script>

<style scoped lang="scss">
  /*每个页面公共css */
  @import '/colorui/main.css';
  @import '/colorui/icon.css';
  @import '/style/FontStyle.css';

  .page {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #FFFFFF;
  }

  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 240rpx;

    image {
      width: 160rpx;
      height: 160rpx;
    }
  }

  /* 填写 */
  .input-info {
    padding: 0 6%;
    height: 240rpx;

    .info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 100%;
      height: 100rpx;
      border-bottom: 2rpx solid #f6f6f6;

      input {
        width: 70%;
        height: 100%;
        font-size: 26rpx;
        color: #222222;
      }

      .more {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        width: 30%;
        height: 100%;

        .iconfont {
          font-size: 34rpx;
        }

        .mo {
          font-size: 26rpx;
          padding-left: 20rpx;
          margin-left: 10rpx;
          border-left: 2rpx solid #EEEEEE;
        }
      }
    }
  }

  /* 按钮 */
  .btn-info {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100rpx;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 90%;
      height: 80rpx;
      background: linear-gradient(to right, $base, $change-clor);
      border-radius: 100rpx;
      color: #FFFFFF;
      font-size: 28rpx;
      opacity: 0.4;
    }
  }

  /* 操作 */
  .operation {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 6%;
    height: 80rpx;

    text {
      font-size: 28rpx;
      color: #555555;
    }
  }

  /* 其他 */
  .other-ways {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 80rpx;
    margin-top: 100rpx;

    text {
      font-size: 28rpx;
      color: #999999;
    }
  }

  .other-ways::after {
    content: "";
    width: 36%;
    height: 2rpx;
    background-color: #EEEEEE;
  }

  .other-ways::before {
    content: "";
    width: 36%;
    height: 2rpx;
    background-color: #EEEEEE;
  }

  /* 登录方式 */
  .login-way {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 200rpx;

    .way {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 50%;
      height: 100%;

      image {
        width: 100rpx;
        height: 100rpx;
      }

      text {
        font-size: 28rpx;
        color: #959595;
        margin-top: 20rpx;
      }
    }
  }
</style>
